<template>
  <div>
    <el-select
      v-model="selectedValue"
      multiple
      filterable
      placeholder="请选择标签"
      :style="{ width: '100%' }"
    >
      <el-option
        v-for="item in selectOptions"
        :key="item.value"
        :label="item.label"
        :value="String(item.value)"
      />
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'MulSelector',
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    options: {
      type: [Array, Object, Function, Promise],
      default() {
        return []
      }
    }
  },
  data() {
    return {
      selectedValue: this.value,
      selectOptions: []
    }
  },
  computed: {
    isIndeterminate() {
      return this.selectedValue.length > 0 && this.selectedValue.length < this.selectOptions.length
    },
    checkAll: {
      get() {
        return this.selectedValue.length === this.selectOptions.length
      },
      set(value) {
        this.selectedValue = value ? this.selectOptions.map(el => el.value) : []
      }
    }
  },
  watch: {
    selectedValue() {
      this.$emit('input', this.selectedValue)
    },
    async options() {
      this.selectOptions = await this.getOptions()
    },
    value() {
      this.selectedValue = this.value
    }
  },
  async created() {
    this.selectOptions = await this.getOptions()
  },
  methods: {
    async getOptions() {
      if (Array.isArray(this.options)) {
        return this.options
      }
      if (this.options instanceof Promise) {
        return await this.options
      }
      return this.options.getOptions()
    }
  }
}
</script>

<style scoped lang="scss">
.space-x-10 > * {
  + * {
    margin-left: 10px;
  }
}
</style>
